Click here to Skip to main content
15,887,083 members
Articles / Programming Languages / C#
Article

How to: Create a generic webpart SharePoint

Rate me:
Please Sign up or sign in to vote.
4.50/5 (4 votes)
16 Aug 2009CPOL6 min read 60.8K   418   14   6
In this article we will discuss how to create a generic webpart in SharePoint

Introduction

This article explains the mechanics of Generic Webpart and demonstrates how to build a Generic Webpart. The document explains the steps required in simple terms. The document is intended to help a beginner, in SharePoint Customization.

Before going deep into Generic Web Part development, we should understand the need of customization in Sharepoint and the situation in which we will go for customization. As per the best practices for Sharepoint, it is better to go for Sharepoint Customization only if the ratio between the “Out of Box” features (Sharepoint Default Features) and customization is 80/20.

Customization should be taken into consideration only when none of the “Out of Box” features matches the user requirement. For ex: In a banking site, you need to calculate the monthly compound interest for a customer based on the minimum amount in a month. These kinds of scenarios are suitable to go for Customization.

Sharepoint customizations can be created in three different ways.

  1. User customizations using standard SharePoint capabilities.
  2. No-code customizations using SharePoint Designer.
  3. Coded customizations using Visual Studio or ASP.Net applications

Creating Custom Web Parts Using WSS3.0 Web Part Template:

Microsoft Visual Studio 2005 extensions for Microsoft Windows SharePoint Services 3.0 include project templates that enable us to jumpstart our development work for the Windows SharePoint Services environment.

Creating a New Web Part Solution

The Web Part project template included in the extensions is customized especially for creating Web Parts for the Windows SharePoint Services environment.

To create a new Web Part solution

1.Open Microsoft Visual Studio 2005.

2.On the File menu, click New, and then select Project.

3.In Project types, select Visual C#, and then select SharePoint.

Note: Currently, the extensions Web Part template supports only Microsoft Visual C#.

4.In Templates, select Web Part.

5.Specify a new name, location, or solution name for the Web Part, and then click OK. The extensions create a new Web Part solution project, which includes the following:

i)References to the necessary DLLs

ii)AssemblyInfo.cs, a file that enables us to specify company and product information for the Web Part assembly, and version information

iii)Temporary.snk, a temporary signature key file for the Web Part assembly

Note: This temporary signature key file is only for development purposes. We must generate our own permanent signature key file when our Web Part assembly is ready for production.

iv)A folder named “Web Part1” which contains three files:

a)A Webpart1.cs file

b)A Webpart1.xml file

c)A Webpart1.webpart file

6.Delete the folder named “Webpart1” from the project

7.In the Solution Explorer right click the newly created Web part project and select Add | New Item

8.In the Categories area of the Add New Item dialogue box select SharePoint and in the Templates area select Web Part

9.Give a suitable name to the Web part and click Add

10.Right click the Web part project and select Properties. The Project Properties will be displayed

11.Select the Debug tab.

12.Set the Start URL to a valid URL of the site on which you want to deploy your Web part. This is used by VSeWSS to determine the location of SharePoint when deploying the solution

13.Open the .webpart file and change the Title and Description as desired.

14.Now code the .CS file for the controls as desired.

15.Build the project and deploy the web part to the location defined in step 12.

Using the code

The following example explains the use of Interest Calculation Generic Web Part, which calculates Simple as well as Compound Interest:

1.Open a web part project as explained in steps above.

2.Change the .webpart file with desired Title and Description. As highlighted in Snippet 1.

XML
<properties>

<p style="LINE-HEIGHT: normal"><property name="Title" type="string">MyWebPart</property>
</p>

<p style="LINE-HEIGHT: normal"><property name="Description" type="string">This is a intrest 
</p>

<p style="LINE-HEIGHT: normal">calculating webpart.</property>
</p>

<p style="LINE-HEIGHT: normal"></properties>

</p>

Snippet 1

3.In the .CS file CreateChildControl method will resemble the code, as in Snippet 2.

C#
protected override void CreateChildControls()
    {
   base.CreateChildControls();
   
   // TODO: add custom rendering code here.
   Label label = new Label();
   label.Text = "My Generic Web Part";
   this.Controls.Add(label);
   }

Snippet 2

4.The next step is to add properties to the Web part. Write the code as in Snippet 3 in the Web part Class.

C#
private double _principal=10000;
   public double Principal
   {
     get { return _principal; }
     set { _principal = value; }
   }
  private double _rateofinterest = 5;
   public double RateofInterest
   {
     get { return _rateofinterest; }
     set { _rateofinterest = value; }
   }
  private double _time = 2;
   public double Time
   {
     get { return _time; }
     set { _time = value; }
   }

Snippet 3

5.In order for SharePoint to display the Web part property for user modification, you must add few attributes to the properties, before that add the following using statement on the top of the .CS File:

C#
using System.ComponentModel

Snippet 4

6.Also you will have to add the attributes to the properties as shown in Snippet 5:

C#
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Enter the principal amount"),
Category("Custom Properties"),
WebDisplayName("Principal")]
   public double Principal
   {
get { return _principal; }
set { _principal = value; }
   }

[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Enter the Rate of Interest"),
Category("Custom Properties"),
WebDisplayName("Rate of Interest")]
   public double RateofInterest
   {
        get { return _rateofinterest; }
        set { _rateofinterest = value; }
   }

Snippet 5

7.Set the attributes for all the properties that you want to be modified by the user.

8.The description of the attributes used is shown in the table below:

Table 2: Attributes of Properties and their Description

Attribute

Description

WebBrowsable(true)

This is used to allow Editing of the Web Part property. Without this the property will not be displayed in the Web Part task pane.

WebDisplayName ("…")

This attribute defines the text that is used to label the property in the Web Part task pane.

Personalizable(PersonalizationScope.User)

User scope means that personalized data will be user-specific.

WebDescription ("…")

This is an optional attribute and can contain anything you define. The description is displayed as a tooltip when hovering over the property in the Web Part task pane.

Category ("…")

This optional attribute is an organizing mechanism, defining where the property should reside in the Web Part task pane of SharePoint and also providing a grouping strategy for logically related properties. The default category is Miscellaneous.

9.The final CreateChildControl method will resemble the following code:

C#
protected override void CreateChildControls()
{
     base.CreateChildControls();
     // TODO: add custom rendering code here.
     Label label = new Label();
     if (string.IsNullOrEmpty(Name))
     {
        Name = "Guest";
     }

     if (InterestType.ToString().Equals("SimpleInterest"))
     {
        Amount = Principal + ((Principal * RateofInterest * Time) / 100);
     }
     else
     {
        //Code for Compound Interest. Omitted for brevity
     }
     label.Text = string.Format("Hello {0}, the amount for your principal 
Rs.{1} with {2} of {3}% for {4} years is {5}",
Name, Principal, InterestType, RateofInterest, Time, Amount);
 
    label.ForeColor = Color.FromKnownColor(Mycolor);
    this.Controls.Add(label);
    }

Snippet 6

10.Deploying and testing the web part: The steps to deploy and test the web part are as follows-

a)Right click the web part project and select “Properties”.

b)In the project properties window select the “Debug” tab and set the “start browser with url” to http://myserver/ (Note: The path is one where the web part will be deployed).

c)Build and deploy the web part by right clicking the web part project and selecting “Deploy”.

d)The status bar should display “Deploy Succeeded”.

e)Navigate to the Sharepoint site you provided in step 10(b).

f)Select Site Actions|Edit Page located on the top right corner of the page.

Site_Actions.JPG

g)Click Add a Web Part at the top of the Left Web Part zone.

AddWebPart.JPG

h)Scroll to All WebParts|Miscellaneous|My WebPart and tick the check box.

AddwebpartDialog1.JPG

i)Click Add. The selected WebPart will be added to the page displaying the default message.

Default_Look.JPG

j)To edit the webpart click “Edit” and select “Modify Shared Web part”.

Edit.JPG

k)In the webpart task pane that appears, expand the “Custom Properties” section.

Custom_Properties.JPG

m)Click OK and web part will display the modifications.

Output.JPG

This completes the example of how to create a Generic Web Part.

Summary

In this article, we explored how we can create a Generic Web Part, which could be used across various applications in Sharepoint. A Generic WebPart helps the developer where there is a need of slight modifications and uses it in a different way, as discussed in the example. The web part sample created can be used for Simple Interest Calculation as well as Compound Interest Calculations.

References

MSDN Article

MSDN Walkthrough

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) MindTree Ltd.
India India
Pawan is a Senior Software Developer for MindTree Ltd. He is currently working in Bangalore as a SharePoint Developer. He has a passion towards technology. Apart from SharePoint, he has also worked on various tools such as SilverLight and Windows Workflows. His total IT experience is 42 months.

His native is Jodhpur, Rajasthan.

Comments and Discussions

 
GeneralDeploy Failed Pin
shalini.nikharey1-Jun-11 20:50
shalini.nikharey1-Jun-11 20:50 
GeneralRe: Deploy Failed Pin
Pawan Jajoo11-Jul-11 22:16
Pawan Jajoo11-Jul-11 22:16 
GeneralError while deploying the webpart into WSS Pin
praveen9i12-Sep-09 0:06
praveen9i12-Sep-09 0:06 
GeneralRe: Error while deploying the webpart into WSS Pin
Pawan Jajoo13-Sep-09 7:51
Pawan Jajoo13-Sep-09 7:51 
GeneralThank man Pin
Yanela Somdaka17-Aug-09 4:04
Yanela Somdaka17-Aug-09 4:04 
GeneralRe: Thank man Pin
Pawan Jajoo19-Aug-09 9:06
Pawan Jajoo19-Aug-09 9:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.